package com.itheima.thread.volatileTest;

/**
 * @Author: Ethan Yankang
 * @Program: Interview
 * @Date: 2024-08-05 22:25
 **/
class VolatileTest {
        int data = 0;
//        volatile boolean ready = false;
         boolean ready = false;
        static int i=0;
        public void write() {
            data = 42;      // 1. 写入数据
            ready = true;   // 2. 设置标志
            if ((i++)==1000){
                System.out.println("写入成功"+i);
            }

        }

        public void read() {
            if (ready) {    // 3. 检查标志
                System.out.println("Data: " + data);  // 4. 读取数据
                if (data==0){
                    System.err.println("指令重排序了");
//                    System.exit(0);
                }

            } else {
                System.out.println("Data not ready");
            }
        }
    }

    public class VolatileExample {
        public static void main(String[] args) throws InterruptedException {
            VolatileTest sharedData = new VolatileTest();

            Thread writer = new Thread(() -> {
                for (int i = 0; i < 100000; i++) {
                    sharedData.write();
                }
            });

            Thread reader = new Thread(() -> {
                for (int i = 0; i < 100000; i++) {
                    sharedData.read();
                }
            });

            writer.start();
            Thread.sleep(10);  // 确保writer线程先运行
            reader.start();

            writer.join();
            reader.join();
   }
}
